package com.pku.smart.service;

import com.alibaba.fastjson.JSONObject;
import com.pku.smart.log.MyLog;
import com.pku.smart.trade.exception.BizTradeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import java.util.Map;

@Service
public class SmartPayService {

    private static final MyLog _log = MyLog.getLog(SmartPayService.class);

    @Autowired
    Validator validator;

    /**
     * 参数校验、签名验证
     * @param object
     * @param bindingResult
     */
    public void validateParams(Object object, BindingResult bindingResult){
        validator.validate(object, bindingResult);
        if (bindingResult.hasErrors()) {
            String errorResponse = getErrorResponse(bindingResult);
            _log.error("请求参数异常:{}", errorResponse);
            throw new BizTradeException(BizTradeException.REQUEST_PARAM_ERR, errorResponse);
        }

        Object jsonObject = JSONObject.toJSON(object);
        Map<String, Object> jsonParamMap = JSONObject.parseObject(jsonObject.toString(), Map.class);
        _log.info("parseObject:" + jsonParamMap);

        String reqKey = String.valueOf(jsonParamMap.get("reqKey"));

        // 验证签名数据
//        boolean verifyFlag = PayUtils.verifyPaySign(jsonParamMap, reqKey);
//        if (!verifyFlag){
//            _log.error("参数[{}],MD5签名验证异常reqKey:{}", jsonParamMap, reqKey);
//            throw new BizTradeException(BizTradeException.TRADE_ORDER_ERROR, "订单签名异常");
//        }
    }

    /**
     * 获取错误返回信息
     *
     * @param bindingResult
     * @return
     */
    public String getErrorResponse(BindingResult bindingResult) {
        StringBuffer sb = new StringBuffer();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            sb.append(objectError.getDefaultMessage()).append(",");
        }
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }
}
